﻿using AIStudio.Core;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace AIStudio.Wpf.Service.AppClient.HttpClients
{
    public class HttpClientHelper
    {
        private static HttpClientHelper instance = null;
        private static object obj = new object();
        private IHttpClientFactory httpClientFactory;

        public static HttpClientHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (obj)
                    {
                        if (instance == null)
                        {
                            instance = new HttpClientHelper();
                            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
                            instance.httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
                        }
                    }
                }
                return instance;
            }
        }      

        /// <summary>
        /// 记录日志
        /// </summary>
        public Action<string> HandleLog { get; set; }


        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="json">发送的参数字符串，只能用json</param>
        /// <returns>返回的字符串</returns>
        public async Task<string> PostAsyncJson(string url, string json, Dictionary<string, string> header = null, TimeSpan? timeSpan = null)
        {
            HttpClient client = httpClientFactory.CreateClient();
            if (timeSpan.HasValue)
            {
                client.Timeout = timeSpan.Value;
            }
            HttpContent content = new StringContent(json);
            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            string responseBody = string.Empty;
            string resData = string.Empty;
            DateTime startTime = DateTime.Now;

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
                resData = responseBody;
            }
            catch (Exception ex)
            {
                resData = $"异常:{ExceptionHelper.GetExceptionAllMsg(ex)}";

                throw ex;
            }
            finally
            {
                var time = DateTime.Now - startTime;
                if (resData?.Length > 1000)
                {
                    resData = resData.Substring(0, 1000);
                    resData += "......";
                }

                string log =
$@"方向:请求外部接口
url:{url}
method:{"Post"}
耗时:{(int)time.TotalMilliseconds}ms

返回:{resData}
";
                HandleLog?.Invoke(log);
            }

            return responseBody;
        }

      
    }
}
